<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="700">
    <NDrawerContent :title="$t('dataplatform.datamodel.versionHistory')" :native-scrollbar="false" closable>
      <NTimeline v-if="versions.length > 0">
        <NTimelineItem
          v-for="version in versions"
          :key="version.id"
          :time="version.createTime"
          :title="`${$t('dataplatform.datamodel.version')} ${version.version}`"
        >
          <NCard size="small">
            <template #header>
              <div class="flex justify-between items-center">
                <span class="font-bold">{{ $t('dataplatform.datamodel.version') }} {{ version.version }}</span>
                <span class="text-gray-500 text-sm">{{ version.createBy }}</span>
              </div>
            </template>
            <div v-if="version.changeDescription" class="mb-3 p-2 bg-gray-50 rounded">
              {{ version.changeDescription }}
            </div>
            <NDataTable
              :columns="fieldColumns"
              :data="parseFields(version.fields)"
              :max-height="300"
              :scroll-x="800"
              size="small"
            />
          </NCard>
        </NTimelineItem>
      </NTimeline>
      <NEmpty v-else :description="$t('common.noData')" />
    </NDrawerContent>
  </NDrawer>
</template>

<script setup lang="tsx">
import { computed, ref, watch } from 'vue';
import type { DataTableColumns } from 'naive-ui';
import { NIcon } from 'naive-ui';
import { $t } from '@/locales';
import { getVersionHistory, type DataModelVersion, type ModelField } from '@/service/api/dataplatform/datamodel';

interface Props {
  visible: boolean;
  modelId?: number;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'update:visible', visible: boolean): void;
}

const emit = defineEmits<Emits>();

const visible = computed({
  get() {
    return props.visible;
  },
  set(visible) {
    emit('update:visible', visible);
  }
});

const versions = ref<DataModelVersion[]>([]);

const fieldColumns: DataTableColumns<ModelField> = [
  { key: 'name', title: () => $t('dataplatform.datamodel.fieldName'), width: 150 },
  { key: 'type', title: () => $t('dataplatform.datamodel.fieldType'), width: 120 },
  { key: 'length', title: () => $t('dataplatform.datamodel.length'), width: 100 },
  {
    key: 'nullable',
    title: () => $t('dataplatform.datamodel.nullable'),
    width: 80,
    align: 'center',
    render: row => {
      if (row.nullable) {
        return <NIcon color="green"><icon-ic-round-check /></NIcon>;
      }
      return <NIcon color="red"><icon-ic-round-close /></NIcon>;
    }
  },
  {
    key: 'primaryKey',
    title: () => $t('dataplatform.datamodel.primaryKey'),
    width: 80,
    align: 'center',
    render: row => {
      if (row.primaryKey) {
        return <NIcon color="green"><icon-ic-round-check /></NIcon>;
      }
      return null;
    }
  },
  { key: 'comment', title: () => $t('dataplatform.datamodel.comment'), minWidth: 150 }
];

async function loadVersions(id: number) {
  const { data } = await getVersionHistory(id);
  versions.value = data;
}

function parseFields(fieldsJson: string): ModelField[] {
  try {
    return JSON.parse(fieldsJson);
  } catch {
    return [];
  }
}

watch(
  () => props.modelId,
  val => {
    if (val && props.visible) {
      loadVersions(val);
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="scss"></style>
